<template>
  <div class="administrationBox">
    <div class="administrationHeader">
      <div class="administrationHeader-body">
        <el-form ref="listQuery" :inline="true" :model="listQuery">
          <el-form-item label="设备编号">
            <el-select v-model="listQuery.equipmentNumber" placeholder="设备编号" clearable>
              <el-option v-for="item in equipmentNumberOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="管理人员">
            <el-select v-model="listQuery.principal" placeholder="管理人员" clearable>
              <el-option v-for="item in principalOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="管理单位">
            <el-select v-model="listQuery.management" placeholder="区域" clearable>
              <el-option v-for="item in managementOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属区域">
            <el-select v-model="listQuery.region" placeholder="区域" clearable>
              <el-option v-for="item in regionOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属省份">
            <el-select v-model="listQuery.province" placeholder="省份" clearable>
              <el-option v-for="item in provinceOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属站点">
            <el-select v-model="listQuery.site" placeholder="站点" clearable>
              <el-option v-for="item in siteOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select v-model="listQuery.equipmentType" placeholder="设备类型" clearable>
              <el-option v-for="item in equipmentTypeOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属管线">
            <el-select v-model="listQuery.pipeline" placeholder="省份" clearable>
              <el-option v-for="item in pipelineOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="排列顺序">
            <el-select v-model="listQuery.sort" @change="handleFilter">
              <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">
              查询
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-edit" @click="handleCreate">
              添加
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-waves :loading="downloadLoading" type="primary" icon="el-icon-download" @click="handleDownload">
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </div>

    </div>
    <div class="administrationBody">
      <div class="administrationBodyTable">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
        >
          <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>

          <el-table-column label="设备名称" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.equipmentName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="设备编号" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.equipmentNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备类型" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.equipmentType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="信号强度" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.signalStrength }}</span>
            </template>
          </el-table-column>

          <el-table-column label="电量(%)" min-width="30px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.electricQuantity }}</span>
            </template>
          </el-table-column>

          <el-table-column label="设备状态" min-width="30px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.state }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上传频率" min-width="30px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.uploadFrequency }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属区域" min-width="30px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.region }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属管线" min-width="30px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.pipeline }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属站点" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.site }}</span>
            </template>
          </el-table-column>
          <el-table-column label="管理单位" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.management }}</span>
            </template>
          </el-table-column>
          <el-table-column label="负责人" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.principal }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备添加时间" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.additionTime | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最近巡检时间" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.patrolInspectionTime | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最近上线时间" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.onlineTime | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="lng" min-width="20px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.lng }}</span>
            </template>
          </el-table-column>
          <el-table-column label="lat" min-width="20px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.lat }}</span>
            </template>
          </el-table-column>
          <el-table-column label="SIM卡编号" min-width="30px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.SIMNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="20px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设置" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>
              <el-button v-if="row.status!=='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.amount" @pagination="getList" />
    </div>
    <div class="administrationFooter">
      <div>
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:70px;">

            <el-form-item label="设备编号" prop="equipmentNumber">
              <el-select v-model="temp.equipmentNumber" placeholder="设备编号" @change="handleFilter">
                <el-option v-for="(item,index) in trueEquipmentOptions" :key="index+item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>

            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="temp.equipmentName" />
            </el-form-item>

            <el-form-item label="设备类型" prop="equipmentType">
              <el-input v-model="temp.equipmentType" />
            </el-form-item>

            <el-form-item label="信号强度" prop="signalStrength">
              <el-input v-model="temp.signalStrength" :disabled="true" />
            </el-form-item>

            <el-form-item label="设备电量" prop="electricQuantity">
              <el-input v-model="temp.electricQuantity" :disabled="true" />
            </el-form-item>

            <el-form-item label="设备状态" prop="state">
              <el-input v-model="temp.state" />
            </el-form-item>

            <el-form-item label="上传频率" prop="uploadFrequency">
              <el-input v-model="temp.uploadFrequency" />
            </el-form-item>

            <el-form-item label="所属省份" prop="province">
              <el-input v-model="temp.province" />
            </el-form-item>

            <el-form-item label="所属站点" prop="site">
              <el-input v-model="temp.site" />
            </el-form-item>

            <el-form-item label="所属区域" prop="region">
              <el-input v-model="temp.region" />
            </el-form-item>

            <el-form-item label="所属管线" prop="pipeline">
              <el-input v-model="temp.pipeline" />
            </el-form-item>

            <el-form-item label="管理单位" prop="management">
              <el-input v-model="temp.management" />
            </el-form-item>

            <el-form-item label="负责人" prop="principal">
              <el-input v-model="temp.principal" />
            </el-form-item>

            <el-form-item label="设备添加时间" prop="additionTime">
              <el-date-picker v-model="temp.additionTime" type="datetime" style="width:280px" placeholder="请选择设备添加时间" />
            </el-form-item>

            <el-form-item label="最近巡检时间" prop="patrolInspectionTime ">
              <el-date-picker v-model="temp.patrolInspectionTime " type="datetime" style="width:280px" placeholder="请选择最近巡检时间" />
            </el-form-item>

            <el-form-item label="最近上线时间" prop="onlineTime">
              <el-date-picker v-model="temp.onlineTime" type="datetime" style="width:280px" placeholder="请选择最近上线时间" />
            </el-form-item>

            <el-form-item label="lng" prop="lng">
              <el-input v-model="temp.lng" />
            </el-form-item>

            <el-form-item label="lat" prop="lat">
              <el-input v-model="temp.lat" />
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" style="width:400px" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              关闭
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              提交
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>

</template>

<script>
import { fetchList, createEquipment, updateEquipment, deleteEquipment, fetchOptions, fetchTrueEquipmentOptions } from '@/api/administration'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },

  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        amount: 10,
        province: '',
        region: '',
        pipeline: '',
        site: '',
        equipmentType: '',
        management: '',
        principal: '',
        equipmentNumber: '',
        sort: '+id'
      },
      sortOptions: [{ label: 'ID 升序', key: '+id' }, { label: 'ID 降序', key: '-id' }],
      showReviewer: false,
      temp: {
        id: undefined,
        equipmentNumber: '',
        equipmentName: '',
        equipmentType: '',
        signalStrength: '',
        electricQuantity: '',
        state: '',
        uploadFrequency: '',
        province: '',
        region: '',
        pipeline: '',
        site: '',
        management: '',
        principal: '',
        additionTime: new Date(),
        patrolInspectionTime: new Date(),
        onlineTime: new Date(),
        SIMNumber: '',
        remark: '',
        lng: '',
        lat: ''

      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        lng: [{ required: true, message: '请输入设备lng', trigger: 'blur' }],
        lat: [{ required: true, message: '请输入设备lat', trigger: 'blur' }],
        equipmentNumber: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
        equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        equipmentType: [{ required: true, message: '请输入设备类型', trigger: 'blur' }],
        signalStrength: [{ required: false, message: '请输入信号强度', trigger: 'blur' }],
        electricQuantity: [{ required: false, message: '请输入电量', trigger: 'blur' }],
        state: [{ required: true, message: '请输入设备状态', trigger: 'blur' }],
        uploadFrequency: [{ required: true, message: '请输入上传频率', trigger: 'blur' }],
        province: [{ required: true, message: '请输入所属省份', trigger: 'blur' }],
        region: [{ required: true, message: '请输入所属区域', trigger: 'blur' }],
        pipeline: [{ required: true, message: '请输入所属管线', trigger: 'blur' }],
        site: [{ required: true, message: '请输入所属站点', trigger: 'blur' }],
        management: [{ required: true, message: '请输入管理单位', trigger: 'blur' }],
        principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
        additionTime: [{ required: true, message: '请选择添加时间', trigger: 'change' }],
        patrolInspectionTime: [{ required: true, message: '请选择最近巡检时间', trigger: 'change' }],
        onlineTime: [{ required: true, message: '请选择最近上线时间', trigger: 'change' }],
        SIMNumber: [{ required: false, message: '请输入SIM卡编号', trigger: 'blur' }]
      },
      downloadLoading: false,
      equipmentNumberOptions: '',
      principalOptions: '',
      equipmentTypeOptions: '',
      stateOptions: '',
      provinceOptions: '',
      regionOptions: '',
      siteOptions: '',
      uploadFrequencyOptions: '',
      managementOptions: '',
      pipelineOptions: '',
      trueEquipmentOptions: ''
    }
  },
  created() {
    this.getList()
    this.getAllOptions()
  },
  methods: {
    getList() {
      // this.updateData()
      this.listLoading = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        equipmentNumber: '',
        equipmentName: '',
        equipmentType: '',
        signalStrength: '',
        electricQuantity: '',
        state: '',
        uploadFrequency: '',
        province: '',
        region: '',
        pipeline: '',
        site: '',
        management: '',
        principal: '',
        additionTime: new Date(),
        patrolInspectionTime: new Date(),
        onlineTime: new Date(),
        SIMNumber: '',
        remark: '',
        lng: '',
        lat: ''
      }
    },
    handleCreate() {
      this.getTureEquipmentOptions()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createEquipment(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.time = new Date(this.temp.time)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.getList()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.time = +new Date(tempData.time) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateEquipment(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改完成',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.getList()
      const temWaiters = this.list[index]
      deleteEquipment(temWaiters.id).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['equipmentNumber', 'equipmentName', 'equipmentType', 'signalStrength', 'electricQuantity', 'state', 'uploadFrequency', 'province', 'region ', 'site', 'management', 'principal', 'additionTime', 'patrolInspectionTime', 'onlineTime', 'lng', 'lat', 'SIMNumber', 'remark']
        const filterVal = ['equipmentNumber', 'equipmentName', 'equipmentType', 'signalStrength', 'electricQuantity', 'state', 'uploadFrequency', 'province', 'region ', 'site', 'management', 'principal', 'additionTime', 'patrolInspectionTime', 'onlineTime', 'lng', 'lat', 'SIMNumber', 'remark']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if ((j === 'additionTime') || (j === 'patrolInspectionTime') || (j === 'onlineTime')) {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    getAllOptions() {
      fetchOptions().then(response => {
        this.equipmentNumberOptions = response.data.equipmentNumberOptions
        this.principalOptions = response.data.principalOptions
        this.managementOptions = response.data.managementOptions
        this.regionOptions = response.data.regionOptions
        this.siteOptions = response.data.siteOptions
        this.pipelineOptions = response.data.pipelineOptions
        this.managementOptions = response.data.managementOptions
        this.equipmentTypeOptions = response.data.equipmentTypeOptions
        this.provinceOptions = response.data.provinceOptions
        this.stateOptions = response.data.stateOptions
        this.uploadFrequencyOptions = response.data.uploadFrequencyOptions
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getTureEquipmentOptions() {
      fetchTrueEquipmentOptions().then(response => {
        this.trueEquipmentOptions = response.data
      })
    }
  }
}
</script>

<style scoped>
.administrationBox {
  display: flex;
  flex-direction: column;
}
.administrationHeader-body{
  padding: 10px;
}
.administrationBody {

}
.administrationHeader{
  display: flex;
  justify-content: space-around;
}
.administrationBodyTable{
  padding: 10px;
}
</style>
